package bluejack.operation;
import nme.display.DisplayObject;
import nme.display.Loader;
import nme.errors.Error;
import nme.events.Event;
import nme.events.IOErrorEvent;
import nme.events.ProgressEvent;
import nme.net.URLRequest;

/**
 * ...
 * @author BlueJack
 */

class LoadOper extends Oper
{
	public var url:String;

	private var loader:Loader;
	
	public function new(url:String=null) {
		this.url = url;
		super();
	}
	
	public function getData():DisplayObject {
		return loader.contentLoaderInfo.content;
	}
	
	override public function execute():Void {
		loader = new Loader();
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, result);
		loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, fault);
		loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		try {
			loader.load(new URLRequest(url));
		}catch (err:Error) {
			trace("Error loading requested document: " + url);
		}
		super.execute();
	}
	
	private function progressHandler(event:ProgressEvent):Void {
			dispatchEvent(event);
	}
	
	override private function end(event:Dynamic = null):Void {
		loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, result);
		loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, fault);
		loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
		super.end(event);
	}
}